import json
import os

stuinfo = {}
shoppingcart = {}
purchased = {}
flag = 1
# 读取 accountinfo.txt 文件中的数据
if os.path.exists("accountinfo.txt"):
    fp = open("accountinfo.txt")
    account_str = fp.read()
    stuinfo = json.loads(account_str)
    fp.close()

# 读取goods.txt文件中的数据
fp = open("goods.txt", encoding="utf-8")
goods_str = fp.read()
goods_info = json.loads(goods_str)
fp.close()

# 登录验证功能
def login(username, password):
    d1 = {username: password}
    if username in stuinfo:
        if d1.get(username) == stuinfo.get(username):
            return 0
        else:
            return 1
    else:
        return 1

# 注册功能
def register(username,password):
    stuinfo[username] = password
    stuinfo_str = json.dumps(stuinfo)
    fp = open("accountinfo.txt", "w")
    fp.write(stuinfo_str)
    fp.close()
    print("注册成功！")


# 商品信息
def goods():
    print(goods_info)
#购物车功能
def ShoppingCart(id):
    shoppingcart[id] = goods_info[id]
    print(f"购物车中的商品为：{shoppingcart}")
#结算功能
def check(budget, purchased):
    sum = 0
    for i in shoppingcart:
        sum += shoppingcart[i]["price"]
    if budget >= sum:
        budget -= sum
        print("购买成功")
        print(shoppingcart)
        purchased.update(shoppingcart)
        shoppingcart.clear()
    else:
        print("余额不足")
    return budget

#退出功能

print("=================欢迎光临三乐购物系统=================")
while 1:
    if flag == 0:
        break
    print("1、登录账号")
    print("2、注册账号")
    choice = input("请进行选择")
    if choice == "1":
        username = input("请输入账号")
        password = input("请输入密码")
        flag = login(username, password)
        if flag == 0:
            print(f"{username}已登录，欢迎光临")
            budget = int(input("请输入购物预算金额"))
            while 1:
                print("1、查看商品")
                print("2、加入购物车")
                print("3、结算")
                print("4、退出")
                choice1 = input("请进行选择")
                if choice1 == "1":
                    goods()
                elif choice1 == "2":
                    goods_id = input("请输入你想加入购物车的商品编号(F0001~F0004)")
                    ShoppingCart(goods_id)
                elif choice1 == "3":
                    budget = check(budget, purchased)
                elif choice1 == "4":
                    print(f"购买明细为{purchased},预算余额还剩{budget}元")
                    flag = 0
                    break
        else:
            print("账号或密码错误")
    elif choice == "2":
        username = input("请输入用户名:")
        password = input("请输入密码:")
        register(username,password)
    elif choice == "exit":
        break










